<template>
  <div class="settings-container">
    <el-card class="settings-card">
      <template #header>
        <div class="card-header">
          <h3>系统状态</h3>
          <el-button 
            type="primary" 
            @click="fetchSettings"
            :loading="loading"
          >
            刷新
          </el-button>
        </div>
      </template>

      <div class="settings-form" v-loading="loading">
        <!-- 系统基础信息 -->
        <div class="settings-group">
          <h4 class="group-title">系统基础信息</h4>
          <div class="status-grid">
            <div class="status-item">
              <div class="status-label">CPU使用率</div>
              <el-progress 
                type="dashboard" 
                :percentage="systemInfo.cpu_usage"
                :color="getProgressColor"
              >
                <template #default="{ percentage }">
                  <span class="progress-value">{{ percentage }}%</span>
                </template>
              </el-progress>
            </div>
            <div class="status-item">
              <div class="status-label">内存使用率</div>
              <el-progress 
                type="dashboard" 
                :percentage="systemInfo.memory_usage"
                :color="getProgressColor"
              >
                <template #default="{ percentage }">
                  <span class="progress-value">{{ percentage }}%</span>
                </template>
              </el-progress>
            </div>
            <div class="status-item">
              <div class="status-label">磁盘使用率</div>
              <el-progress 
                type="dashboard" 
                :percentage="systemInfo.disk_usage"
                :color="getProgressColor"
              >
                <template #default="{ percentage }">
                  <span class="progress-value">{{ percentage }}%</span>
                </template>
              </el-progress>
            </div>
          </div>
        </div>

        <!-- 数据统计信息 -->
        <div class="settings-group">
          <h4 class="group-title">数据统计信息</h4>
          <div class="status-grid">
            <div class="status-item">
              <el-statistic title="电影总数" :value="dataStats.total_movies">
                <template #prefix>
                  <el-icon><Film /></el-icon>
                </template>
              </el-statistic>
            </div>
            <div class="status-item">
              <el-statistic title="用户总数" :value="dataStats.total_users">
                <template #prefix>
                  <el-icon><User /></el-icon>
                </template>
              </el-statistic>
            </div>
            <div class="status-item">
              <el-statistic title="活跃用户" :value="dataStats.active_users">
                <template #prefix>
                  <el-icon><UserFilled /></el-icon>
                </template>
              </el-statistic>
            </div>
            <div class="status-item">
              <el-statistic title="管理员数" :value="dataStats.admin_users">
                <template #prefix>
                  <el-icon><Avatar /></el-icon>
                </template>
              </el-statistic>
            </div>
          </div>
        </div>

        <!-- 数据分析信息 -->
        <div class="settings-group">
          <h4 class="group-title">数据分析信息</h4>
          <div class="status-grid">
            <div class="status-item">
              <el-statistic title="本周新增电影" :value="dataAnalysis.new_movies_week">
                <template #prefix>
                  <el-icon><Plus /></el-icon>
                </template>
              </el-statistic>
            </div>
            <div class="status-item">
              <el-statistic title="本周更新电影" :value="dataAnalysis.updated_movies_week">
                <template #prefix>
                  <el-icon><Refresh /></el-icon>
                </template>
              </el-statistic>
            </div>
          </div>
        </div>

        <!-- 系统运行状态 -->
        <div class="settings-group">
          <h4 class="group-title">系统运行状态</h4>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="作者">
              陈旭
            </el-descriptions-item>
            <el-descriptions-item label="Python版本">
              {{ systemStatus.python_version }}
            </el-descriptions-item>
            <el-descriptions-item label="数据库类型">
              {{ systemStatus.database_type }}
            </el-descriptions-item>
            <el-descriptions-item label="服务器时区">
              {{ systemStatus.server_timezone }}
            </el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import { systemApi } from '@/api/system'
import { Film, User, UserFilled, Avatar, Plus, Refresh } from '@element-plus/icons-vue'

const loading = ref(false)
const systemInfo = ref({
  cpu_usage: 0,
  memory_usage: 0,
  disk_usage: 0
})
const dataStats = ref({
  total_movies: 0,
  total_users: 0,
  active_users: 0,
  admin_users: 0
})
const dataAnalysis = ref({
  new_movies_week: 0,
  updated_movies_week: 0
})
const systemStatus = ref({
  python_version: '',
  database_type: '',
  server_timezone: ''
})

let refreshTimer = null // 添加定时器引用

// 自动刷新系统基础信息
const autoRefreshSystemInfo = () => {
  // 清除可能存在的旧定时器
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
  
  refreshTimer = setInterval(async () => {
    try {
      const res = await systemApi.getSettings()
      if (res.status === 'success') {
        systemInfo.value = res.data.system_info
      }
    } catch (error) {
      console.error('自动刷新系统状态失败:', error)
    }
  }, 1000) // 每秒刷新一次
}

// 清理定时器
onUnmounted(() => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
  }
})

// 获取系统状态
const fetchSettings = async () => {
  loading.value = true
  try {
    const res = await systemApi.getSettings()
    if (res.status === 'success') {
      systemInfo.value = res.data.system_info
      dataStats.value = res.data.data_stats
      dataAnalysis.value = res.data.data_analysis
      systemStatus.value = res.data.system_status
    }
  } catch (error) {
    console.error('获取系统状态失败:', error)
    ElMessage.error('获取系统状态失败')
  } finally {
    loading.value = false
  }
}

// 格式化运行时间
const formatUptime = (uptime) => {
  const now = Math.floor(Date.now() / 1000)
  const diff = now - uptime
  const days = Math.floor(diff / 86400)
  const hours = Math.floor((diff % 86400) / 3600)
  const minutes = Math.floor((diff % 3600) / 60)
  return `${days}天 ${hours}小时 ${minutes}分钟`
}

// 获取进度条颜色
const getProgressColor = (percentage) => {
  if (percentage < 60) return '#67C23A'
  if (percentage < 80) return '#E6A23C'
  return '#F56C6C'
}

onMounted(() => {
  fetchSettings()
  autoRefreshSystemInfo() // 启动自动刷新
})
</script>

<style scoped>
.settings-container {
  padding: 20px;
  height: 100%;
  box-sizing: border-box;
  background-color: #f5f7fa;
}

.settings-card {
  max-width: 1000px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.settings-group {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.group-title {
  margin: 0 0 20px;
  padding-bottom: 10px;
  font-size: 16px;
  font-weight: 500;
  color: #409EFF;
  border-bottom: 1px solid #EBEEF5;
}

.status-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
  align-items: center;
}

.status-item {
  text-align: center;
}

.status-label {
  margin-bottom: 10px;
  font-size: 14px;
  color: #606266;
}

.progress-value {
  font-size: 20px;
  font-weight: bold;
}

:deep(.el-progress__text) {
  font-size: 14px !important;
}

:deep(.el-statistic__title) {
  font-size: 14px;
  color: #606266;
}

:deep(.el-statistic__content) {
  font-size: 24px;
  color: #303133;
}

:deep(.el-descriptions) {
  margin: 0;
}

:deep(.el-descriptions__cell) {
  padding: 12px 20px;
}
</style> 